package session

import (
	"encoding/json"
	"gitee.com/tangrx/go-admin/utils/redis"
	"github.com/satori/go.uuid"
	"log"
	"time"
)

const SESSION_PRE string = "SESSION:"
const SESSION_TIMEOUT time.Duration = time.Duration(20) * time.Minute
const CODE_TIMEOUT time.Duration = time.Duration(20) * time.Minute

// 获取UUID
func GUUID() string {
	id, _ := uuid.NewV4()
	return id.String()
}

// 获取sessionId
func GSessionID(id string) string {
	return SESSION_PRE + id
}

// 获取session
func GSession(id string, dest interface{}) error {
	key := GSessionID(id)
	str := redis.Get(key)
	log.Println("session:", str)
	if len(str) > 0 {
		redis.EXPIRE(key, SESSION_TIMEOUT) // 更新session 的TTL
	}
	return json.Unmarshal([]byte(str), dest)
}

// 保存Session
func SaveSession(id string, dest interface{}) error {
	str, err := json.Marshal(dest)
	if err != nil {
		return err
	}
	err = redis.Put(GSessionID(id), string(str), SESSION_TIMEOUT)
	if err != nil {
		log.Println("session 保持失败", err)
	}
	return err
}

func getCodeId(id string) string {
	return "CODE:" + id
}

// 保持验证码（当前20分钟）
func SaveCode(id string, code string) {

	redis.Put(getCodeId(id), code, CODE_TIMEOUT)
}

// 获取验证码
func GetCode(id string) string {
	return redis.Get(getCodeId(id))
}
